<template>
  <div class="multiPictureUpload">
    <a-upload v-model:file-list="fileList" class="avatar-uploader" :accept="props.accept" :directory="props.directory"
      :listType="props.listType" :multiple="props.multiple" :progress="progress"
      :isLimit="props.isLimit" @preview="handlePreview" :before-upload="beforeUpload"
      :custom-request="(file: otherType) => handleUpload(file)" :show-upload-list="true" v-if="props.showCard">
      <a-button class="upload_button_line" :disabled="props.maxCount ? fileList.length >= props.maxCount : false">
        <upload-outlined></upload-outlined>
        <span class="iconfont icon-upload"></span>
        {{ props.title }}
      </a-button>
    </a-upload>
    <div class="middle-box">
      <draggable :list="fileData" ghost-class="eghost" handle=".move" filter=".forbid" :force-fallback="true"
        chosen-class="chosenClass" animation="300" @start="onStart" @end="onEnd" sort="true" :fallback-class="true"
        dragClass="dragClass" :fallback-on-body="true" :touch-start-threshold="50" :fallback-tolerance="50" :move="onMove"
        class="drag-box">
        <template #item="{ element, index }">
          <div class="uploadList">
            <!-- <div class="edit-item uploadList"> -->
            <div class="imgContent">
              <img class="imgList" :src="element.url" />
              <div class="uploadList-mask">
                <a-tooltip>
                  <template #title>图片裁剪</template>
                  <span class="iconfont icon-cutting" @click="handleCropper(element)"></span>
                </a-tooltip>
                <a-tooltip>
                  <template #title>图片预览</template>
                  <span class="iconfont icon-preview" @click="handlePreview(element)"></span>
                </a-tooltip>
                <a-tooltip>
                  <template #title>图片删除</template>
                  <span class="iconfont" @click="removePictrues(element)">&#xe8e2;</span>
                </a-tooltip>
              </div>
            </div>
            <a-textarea v-model:value="element.description" class="picDescriptiong" placeholder="请输入" allow-clear
              maxlength="120" show-count :rows="5" v-if="props.description" @blur="addDescription(index)" />
            <!-- <a-progress :percent="pp" size="small" /> -->
            <span class="move drag_move">
              <i class="iconfont"> &#xe90d;</i>
            </span>
            <!-- </div> -->
          </div>
        </template>
      </draggable>
    </div>
    <base-modal :width="modAlProps.width" :isVisible="previewVisible" :title="previewTitle" :isCancleBtn="false"
      :buttons="buttons" @handleCancle="previewVisible = false" class="upload_modal">
      <template v-slot:body>
        <img alt="previewImage" :style="styles" :src="previewImage" />
      </template>
    </base-modal>
    <cropper :isVisible="cropper_isVisible" :src="fileObj.url" :id="fileObj.id" :originFile="fileObj" @handleOk="handleOk"
      @handleCancle="cropper_isVisible = false" v-if="fileList.length"></cropper>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted, reactive } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import cropper from "./oldCropper.vue";
import { message } from "ant-design-vue";
import { MultipleUploadProps } from "./uploadConfig/props";
import { dataSourceType } from "../../type";
import { request } from "@/api/axios";
import draggable from "vuedraggable";
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
//props
const props = defineProps(MultipleUploadProps);
//emit
const emit = defineEmits([
  "uploadChangeFinished",
  "uploadFinished",
  "upload_remove_Finished",
  "addDescription",
  "draggend",
]);
//type
type otherType = {
  [propName: string]: any;
};
//data
const previewVisible = ref<Boolean>(false);
const previewImage = ref<string>("");
const previewTitle = ref<string>("");
const fileList = ref<any>([]);
const fileData = ref<any>([]);

const fileObj = ref<any>([]);
let acceptTypeList = ref<string[]>([]);
let styles = ref<string>("");
const arr1 = ref(props.fileList);
//模态框
const modAlProps = reactive({
  width: "M",
  title: "",
});
const cropper_isVisible = ref<Boolean | any>(false);
const progress = reactive({
  // 重写进度条
  strokeColor: {
    "0%": "#1890FF",
    "100%": "#1890FF",
  },
  strokeWidth: 2,
  format: (percent = 0) => {
    return `${parseFloat((+percent).toFixed(0))}%`;
  },
  class: "test",
  style: { width: "95%", fontSize: "12px" },
});
const pp = ref<string | number>(0);
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
// watch
watch(
  () => props.fileList,
  (newVal, oldVal) => {
    if (newVal.length) {
      fileList.value = JSON.parse(JSON.stringify(newVal));
      fileData.value = JSON.parse(JSON.stringify(newVal));
      console.log(fileData.value, 'fileData.value');
      // nextTick(() => {
      //   getImageStyle(newVal[0].url);
      // })

    } else {
      fileList.value = [];
      fileData.value = [];
    }
  },
  { deep: true, immediate: true }
);
// methods
//// 删除图片
const removePictrues = (info: any) => {
  fileData.value.map((item: any, index: any) => {
    if (item.id == info.id) {
      fileData.value.splice(index, 1);
    }
  });
  //
  emit("upload_remove_Finished", info);
};
const beforeUpload = (file: otherType["fileList"][number]) => {
  // 文件上传之前的限制条件过滤，有文件类型和文件大小限制。
  return new Promise((resolve, reject) => {
    // beforeUpload必须使用promise 返回false才能阻止change事件，否则无效
    const backgFix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取文件的后缀
    let isFileType = true;
    if (acceptTypeList.value.length) {
      isFileType = acceptTypeList.value.includes(backgFix);

      if (!isFileType) {
        message.error(`只能上传${acceptTypeList.value.join(",")}格式文件!`);
        return false;
      }
    }

    let isLt2M = true;
    if (props.isLimit) {
      isLt2M =
        props.isLimit == 0 ? true : file.size / 1024 / 1024 < props.isLimit;
      if (!isLt2M) {
        message.error(`文件大小不得超过 ${props.isLimit} MB!`);
        return false;
      }
    }
    if (fileList.length > props.maxCount) {

    }

    if (isFileType && isLt2M) {
      //fileList.value = [...fileList.value, file]
      return resolve(true);
    }
  });
};

const handleUpload = (options: otherType) => {
  let id = options?.originId || '';
  if (id) {
    fileData.value.map((item: any, index: any) => {
      if (item.id == id) {
        getBase64(options.file).then((res: any) => {
          let obj = {
            id: options.file.uid,
            url: res,
            file: options.file,
          };
          fileData.value[index] = obj;
        });
      }
    });

    emit("uploadChangeFinished", fileData.value);
  } else {
    getBase64(options.file).then((res: any) => {
      let obj = {
        id: options.file.uid,
        url: res,
        file: options.file,
        options,
      };
      if (fileData.value.length < props.maxCount) {
        fileData.value.push(obj);
      }
      emit("uploadChangeFinished", fileData.value);
    });

  }
  
};

const uploadPic = (files: any[], originId: any) => { // 剪切回调上传
  files.forEach((item: any) => {
    const param = new FormData(); // 创建form对象
    param.append("files", item.file, item.file.name); // 通过append向form对象添加数据
    let headers: Record<string, any> = {
      "Content-Type":
        "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
      noWatermark: 1,
    };
    request
      .post("/server-admin/res/upload", param, {
        headers: headers,
      })
      .then((res: any) => {
        if (res.data.code == "00000 00000") {
          emit("uploadFinished", res.data.data, originId);
          message.success(res.data.message);
        } else {
          message.error(res.data.message);
        }
      })
      .catch((err) => {
        console.log(err, 9999);
      });
  });
};
const handlePreview = async (file: otherType["fileList"][number]) => {
  // 文件预览
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value =
    file.oriFileName || file.name || file.file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};
const onMove = (e: any, item: any) => {
};
const onStart = (e: any) => {
};
//拖拽结束的事件
const onEnd = (e: any) => {
  emit('draggend', fileData.value)
};
const handleCropper = async (file: otherType) => {
  fileObj.value = file;
  cropper_isVisible.value = true;
};
const handleOk = (content: object, id: string, e: object, originFile: any) => {
  cropper_isVisible.value = false;
  let filess = {
    file: content,
    originId: id
  };
  handleUpload(filess);
  if (id) {// 有id时，裁剪直接上传
    uploadPic([filess], id);
  }

};
// 添加图片描述
const addDescription = (index: number) => {
  if (fileData.value[index].filename) {
    emit('addDescription', fileData.value[index].id, fileData.value[index]);
  }
}
// computed
acceptTypeList = computed({
  get() {
    return props.accept ? props.accept.split(",") : [];
  },
  set() { },
});
</script>
<style lang="scss" scoped>
::v-deep(.ant-upload.ant-upload-select-picture-card) {
  width: unset;
  height: unset;
  border: none;
}

.upload_button_line {
  margin-top: -4px;

  .icon-upload {
    margin-right: 6px;
  }
}

.tips {
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}

.iconfont.icon-Add {
  font-size: 24px;
  color: rgba(0, 0, 0, 0.85);
}

.drag-box {
  moz-user-select: -moz-none;
  -moz-user-select: none;
  -o-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;

  .uploadList,
  .eghost {
    margin-bottom: 8px;
    text-align: center;
    border-radius: 2px;
    cursor: default;
    position: relative;
    display: flex;
    justify-content: space-between;
    padding-top: 24px;
    width: fit-content;

    .imgContent {
      vertical-align: top;
      border: 1px solid rgba(0, 0, 0, 0.15);
      width: 104px;
      height: 104px;
      padding: 8px;
      margin-right: 8px;
      box-sizing: border-box;
      position: relative;
      cursor: default;

      .imgList {
        max-width: 88px;
        width: auto;
        max-height: 88px;
        height: auto;
        margin: auto;
      }

      .iconfont {
        cursor: pointer;
      }

      &:hover {
        .uploadList-mask {
          display: block;
        }
      }

      .uploadList-mask {
        background-color: rgba(0, 0, 0, 0.5);
        width: 88px;
        height: 88px;
        margin: 7px;
        box-sizing: border-box;
        position: absolute;
        top: 0;
        left: 0;
        align-items: center;
        justify-content: center;
        display: none;

        .iconfont {
          width: 23px;
          color: rgba(255, 255, 255, 0.8);
        }

        .iconfont:hover {
          color: rgba(255, 255, 255, 1);
        }

        .icon-delete {
          margin-left: 0;
        }
      }

      .uploadList-mask:hover {
        display: flex;
      }
    }

    .picDescriptiong {
      width: 120px;
      min-height: 104px;
      box-sizing: border-box;

      ::deep(textarea.ant-input) {
        line-height: 1.35;
      }

      ::v-deep(.ant-input-textarea-show-count::after) {
        position: absolute;
        right: 12px;
        bottom: 6px;
      }
    }

    .drag_move {
      position: absolute;
      top: -4px;
      right: 1px;

      .iconfont {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);

        &:hover {
          color: rgba(0, 0, 0, 0.65);
        }

        &:active {
          color: rgba(0, 0, 0, 0.85);
        }
      }
    }
  }

  .column-system {
    width: 224px;
  }

  .uploadList:hover {

    cursor: move;


    .text {
      color: #1f6ded;
    }

    .drag-icon {
      color: #1f6ded;
    }
  }
}

.uploadList:hover {
  .uploadList-mask {
    display: flex;
  }
}

// .group {
//   display: flex;
//   flex-direction: column;
//   justify-content: flex-start;
//   align-content: center;
//   width: 32%;
//   margin-right: 20px;
// }
.dragClass {
  display: flex;
  width: fit-content;
  height: fit-content;
  max-width: 100%;
  padding: 8px;
  background-color: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  overflow: hidden;
  box-sizing: border-box;
}

.chosenClass {
  // width: fit-content;
  // height: fit-content;
  // // padding: 8px;
  // display: flex;
  // box-sizing: border-box;
  // overflow: hidden;

  // border: 1px solid #1ec6df;
  .uploadList-mask {
    display: none;
  }
}
</style>
<style lang="scss">
.multiPictureUpload {
  display: block;
  margin-top: 12px;

  // display: flex;
  .middle-box {
    // display: inline-block;
  }

  .ant-upload-picture-card-wrapper {
    // display: inline-block;
    width: 104px;
  }

  .ant-upload-list {
    display: inline-block;
  }

  ::depp .ant-progress-line {
    width: 78px;
    position: absolute;
    left: 12px;
    top: 43px;

    .ant-progress-bg {
      height: 2px !important;
    }
  }

  .ant-progress-status-success {
    display: none;
  }

  .ant-upload-list-picture-card-container {
    display: none;
  }
}
</style>
